package com.ubs.training.web.controller;

import com.ubs.training.server.dao.model.LinkClient;
import com.ubs.training.server.service.LinkClientService;
import com.ubs.training.web.util.LinkClientValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LinkClientController {
    @Autowired
    LinkClientService svlc;

    @RequestMapping(value = "client/{clientId}/linkedclient/list.do", method = RequestMethod.GET)
    public String listLinkClients(Model model) {
        model.addAttribute("linkclients", svlc.getAll());
        return "listlinkclients";
    }

    @RequestMapping(value = "client/{clientId}/linkedclient/{linkClientId}/edit.do", method = RequestMethod.GET)
    public String getClient(@PathVariable("linkClientId") int linkClientId, Model model) {
        LinkClient linkClient;
        if(linkClientId > 0) {
            linkClient = svlc.getByLinkClientId(linkClientId);
        } else {
            linkClient = new LinkClient();
        }
        model.addAttribute("linkclient", linkClient);
        return "editlinkclient";
    }

    @RequestMapping(value = "client/{clientId}/linkedclient/{linkClientId}/delete.do", method = RequestMethod.GET)
    public String deleteLinkClient(@PathVariable("linkClientId") int linkClientId, @ModelAttribute("linkclient") LinkClient linkclient) {
        svlc.removeLinkCLient(linkClientId);
        return "redirect:/client/{clientId}/linkedclient/list.do";
    }

    @RequestMapping(value = "client/{clientId}/linkedclient/{linkClientId}/edit.do", method = RequestMethod.POST)
    public String saveLinkClient(@PathVariable("linkClientId") int linkClientId, @ModelAttribute("linkclient") LinkClient linkclient, BindingResult res) {
        new LinkClientValidator(linkclient, res).validate();
        if(res.hasErrors()) {
            return "editlinkclient";
        }
        linkclient.setId(linkClientId);

        svlc.saveLinkClient(linkclient);
        return "redirect:/client/{clientId}/linkedclient/list.do";
    }
    @RequestMapping(value = "client/{clientId}/linkedclient/{linkClientId}/view.do", method = RequestMethod.GET)
    public String listClients(@PathVariable("clientId") int clientId,Model model) {
        model.addAttribute("listclients", svlc.getByClientID(clientId));
        return "viewclients";
    }





}
